//
//  ViewController.m
//  RecordDemo
//
//  Created by Topsky on 2017/5/18.
//  Copyright © 2017年 Topsky. All rights reserved.
//

#import "ViewController.h"
#import "LFLiveKit.h"
#import "HBVideoChatFoldButton.h"
#import "Masonry.h"

#define screenWidth [UIScreen mainScreen].bounds.size.width

@interface ViewController ()<LFLiveSessionDelegate>
{
    UIButton *playBtn;
}
//当前区域网所在IP地址,也就是本地服务器的IP地址
@property (nonatomic,copy) NSString *ipAddress;
//ip后缀
@property (nonatomic, copy) NSString *suffix;
//我的房间号
@property (nonatomic,copy) NSString *myRoom;
//推流会话
@property (nonatomic,strong) LFLiveSession *session;
//大视图
@property (nonatomic,weak) UIView *bigView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.ipAddress = @"192.168.0.103";
    self.myRoom = @"room";
    //suffix要根据服务器提供的字段名设定,如果搭建本地服务器是写rtmplive就是rtmplive
    self.suffix = @"rtmplive";
    
    //建立UI
    [self setupUI];
    //    录制端
    [self requesetAccessForVideo];
    [self requesetAccessForMedio];
    [self startLive];
    //将preview中的GPUImageView(显示摄像头内容的view)设置成与preView同大小(默认是与屏幕同尺寸)
    for (UIView *view in self.session.preView.subviews) {
        view.frame = self.session.preView.bounds;
    }
}

- (void)setupUI{
    [self setupView];
    [self setupButton];
    playBtn = [UIButton new];
    [playBtn setBackgroundColor:[UIColor whiteColor]];
    [playBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [playBtn setTitle:@"暂停" forState:UIControlStateNormal];
    [playBtn addTarget:self action:@selector(playDidTouch) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:playBtn];
    [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(@40);
    }];
}
//设置显示视图
- (void)setupView{
    UIView *bigView = [[UIView alloc] initWithFrame:self.view.bounds];
    bigView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:bigView];
    self.bigView = bigView;
    UITapGestureRecognizer *tapGestureRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
    [self.bigView addGestureRecognizer:tapGestureRecognizer];
}

//播放、暂停
- (void)playDidTouch{
    if ([self.session state] == LFLiveStart) {
        [self stopLive];
        [playBtn setTitle:@"播放" forState:UIControlStateNormal];
    }else{
        [self startLive];
        [playBtn setTitle:@"暂停" forState:UIControlStateNormal];
    }
}

- (void)handleTap:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded){
        playBtn.hidden = !playBtn.hidden;
    }
}

//设置折叠按钮
- (void)setupButton{
    HBVideoChatFoldButton *button = [[HBVideoChatFoldButton alloc] initWithFrame:CGRectMake(10, 84, 30, 30) mainButtonBGImage:@"video_icon" selectBGImage:@"file_icon" otherButtonsBGimages:@[@"play_music",@"pause_music"]];
    __weak typeof(self)weakSelf = self;
    button.ButtonClickBlock = ^void(UIButton *button) {
        switch (button.tag) {
            case 1:
                [weakSelf changeCamera];
                break;
            case 2:
                [weakSelf changeBeautifulMode];
                break;
            default:
                break;
        }
    };
    [self.view addSubview:button];
}
#pragma mark - 按钮响应
//改变前后美颜效果
- (void)changeBeautifulMode{
    self.session.beautyFace = !self.session.beautyFace;
}

//改变前后摄像头
- (void)changeCamera{
    AVCaptureDevicePosition devicePosition = self.session.captureDevicePosition;
    self.session.captureDevicePosition = (devicePosition == AVCaptureDevicePositionBack) ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
}

#pragma mark - 推流端 开始/停止推流方法
- (void)startLive{
    //RTMP要设置推流地址
    LFLiveStreamInfo *streamInfo = [LFLiveStreamInfo new];
    streamInfo.url = [NSString stringWithFormat:@"rtmp://%@:1935/%@/%@",self.ipAddress,self.suffix,self.myRoom];
    [self.session startLive:streamInfo];
}

- (void)stopLive{
    [self.session stopLive];
}

#pragma mark - 推流段-请求设备授权
/**
 *  请求摄像头资源
 */
- (void)requesetAccessForVideo{
    __weak typeof(self) weakSelf = self;
    //判断授权状态
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status) {
        case AVAuthorizationStatusNotDetermined:{
            //发起授权请求
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //运行会话
                        [weakSelf.session setRunning:YES];
                    });
                }
            }];
            break;
        }
        case AVAuthorizationStatusAuthorized:{
            //已授权则继续
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.session setRunning:YES];
            });
            break;
        }
        default:
            break;
    }
}

/**
 *  请求音频资源
 */
- (void)requesetAccessForMedio{
    __weak typeof(self) weakSelf = self;
    //判断授权状态
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status) {
        case AVAuthorizationStatusNotDetermined:{
            //发起授权请求
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //运行会话
                        [weakSelf.session setRunning:YES];
                    });
                }
            }];
            break;
        }
        case AVAuthorizationStatusAuthorized:{
            //已授权则继续
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.session setRunning:YES];
            });
            break;
        }
        default:
            break;
    }
    
}

#pragma mark - LFLiveSessionDelegate
//状态改变回调
- (void)liveSession:(nullable LFLiveSession *)session liveStateDidChange:(LFLiveState)state{
    //    /// 准备
    //    LFLiveReady = 0,
    //    /// 连接中
    //    LFLivePending = 1,
    //    /// 已连接
    //    LFLiveStart = 2,
    //    /// 已断开
    //    LFLiveStop = 3,
    //    /// 连接出错
    //    LFLiveError = 4
}
//调试回调
- (void)liveSession:(nullable LFLiveSession *)session debugInfo:(nullable LFLiveDebug *)debugInfo{
    NSLog(@"调试信息");
}
//连接错误回调
- (void)liveSession:(nullable LFLiveSession *)session errorCode:(LFLiveSocketErrorCode)errorCode{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:@"连接错误,请检查IP地址后重试" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:sure];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark - 懒加载
- (LFLiveSession *)session{
    if (_session == nil) {
        //初始化session要传入音频配置和视频配置
        //音频的默认配置为:采样率44.1 双声道
        //视频默认分辨率为360 * 640
        _session = [[LFLiveSession alloc] initWithAudioConfiguration:[LFLiveAudioConfiguration defaultConfiguration] videoConfiguration:[LFLiveVideoConfiguration defaultConfigurationForQuality:LFLiveVideoQuality_Low1] ];
        //设置返回的视频显示在哪个view上
        _session.preView = self.bigView;
        _session.delegate = self;
        //是否输出调试信息
        _session.showDebugInfo = NO;
    }
    return _session;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
